package com.ubing.boot.notesforjava.test.file;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannel1 {

    public static void main(String[] args) {
        // FileChannel 文件通道

        try (FileChannel channel = new FileInputStream("D:\\项目\\notesforjava\\src\\main\\java\\com\\ubing\\boot\\notesforjava\\test\\file\\data.txt").getChannel()) {
            // 准备缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            System.out.println(channel.size());
            // 从channel中读取数据到buffer中
            channel.read(buffer);
            System.out.println(channel.position());
            // 打印buffer中的数据
//            System.out.println(new String(buffer.array()));
            buffer.flip();// 将buffer指针位置 置为0
            while (buffer.hasRemaining()){ // 是否有剩余数据
                byte b = buffer.get();
                System.out.println((char) b);
            }
            buffer.clear();
            int position = buffer.position();
            System.out.println(position);
            System.out.println();
        } catch (IOException e) {
        }
    }

}
